import org.apache.log4j.Logger
import org.codehaus.groovy.grails.commons.ApplicationAttributes

import org.springframework.web.context.support.WebApplicationContextUtils
import org.codehaus.groovy.grails.web.context.ServletContextHolder

class DataSourceUtils {
	
	static final Logger log = Logger.getLogger(DataSourceUtils)
	
	//
	// fix for the database killing idle connections
	//
	// http://sacharya.com/grails-dbcp-stale-connections/
	//
	private static final ms = 1000 * 15 * 60
	
	public static tune = { servletContext ->
		
		/*def servletCtx = ServletContextHolder.getServletContext()
		def ctx =
				WebApplicationContextUtils.getWebApplicationContext(servletCtx)
		
		//def ctx = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT)
			//System.err.println("ctx=" + ctx.);
			
			def dataSource = ctx.dataSourceUnproxied
			//println "configuring database connection pool"
			
			dataSource.setMinEvictableIdleTimeMillis(1000 * 60 * 30)
			dataSource.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30)
			dataSource.setNumTestsPerEvictionRun(3)
			dataSource.setTestOnBorrow(true)
			dataSource.setTestWhileIdle(false)//true
			dataSource.setTestOnReturn(false)//true
			dataSource.setValidationQuery("SELECT 1")
			
			//dataSource.properties.each { println it }
		*/
		def ctx = servletContext.getAttribute(ApplicationAttributes.APPLICATION_CONTEXT)
		ctx.dataSource.with {d ->			
			d.setMinEvictableIdleTimeMillis(1000 * 60 * 30)
			d.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30)
			d.setNumTestsPerEvictionRun(3)
			d.setTestOnBorrow(true)
			d.setTestWhileIdle(true)
			d.setTestOnReturn(true)
			d.setValidationQuery('select 1')
			d.setMinIdle(1)
			d.setMaxActive(16)
			d.setInitialSize(8)
		}
		
		if (log.infoEnabled) {
			log.info "Configured Datasource properties:"
			ctx.dataSource.properties.findAll {k, v -> !k.contains('password') }.each {p ->
				log.info "  $p"
			}
		}
	}
}